package com.jiangjiang.eshop.inventory.async;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName StockUpdateManagerImpl
 * @Description TODO
 * @Author jhw
 * @Date 2021/6/14 15:55
 * @Version 1.0
 **/
@Component
public class StockUpdateResultManagerImpl implements StockUpdateResultManager {
    /**
     * 商品库存更新结果map
     */
    private final Map<String, StockUpdateObservable> observableMap = new ConcurrentHashMap<>();
    /**
     * 商品库存更新结果观察者
     */
    @Autowired
    private StockUpdateObserver observer;
    /**
     * 设置观察
     * @param messageId 消息id
     */
    @Override
    public void observe(String messageId) {
        StockUpdateObservable observable = new StockUpdateObservable(messageId);
        observable.addObserver(observer);
        observableMap.put(messageId, observable);
    }

    /**
     * 处理完成后通知观察者
     * @param messageId 商品库存更新消息id
     * @param result 结果
     */
    @Override
    public void inform(String messageId, Boolean result) {
        StockUpdateObservable observable = observableMap.get(messageId);
        observable.setResult(result);
        observableMap.remove(messageId);
    }
}
